import { reactive, ref, onMounted  } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPersonList, getCurrentRoleDetailApi, getCompanyApi, getCurrentMenuApi, selectPersonApi, deleteRoleApi } from '@/api/modules/authority.js'

export const useAddAuthority = () => {
  const authorityForm = ref({
    "name":"",     // 角色名称
    "parentId":0,           // 角色父id
    "explains":"",  // 角色说明
    "companys": [],
    "stat":"ENABLE",       // 角色状态：ENABLE，DISABLE
    "users":[],        // 人员id
    "menus":[],           // 目录id
    "views":[],        // 页面id
    "bottoms":[],       // 按钮id
    "remark":"",            // 角色标识（非必参） 可填：admin和user，默认user
    "roleList":""      
  })
  const formRef = ref(null)
  const treeRef = ref(null)
  const dialogVisible = ref(false)
  const detailVisible = ref(false)
  const defaultProps = ref({
    children: 'children',
    label: 'label',
  })
  const menuDataList = ref([
  ])
  const companyList = ref([])
  const peopleTreeData = ref([])
  const handleClose = () => {
    dialogVisible.value = false
    formRef.value.resetFields()
  }
  const getCompany = async () => {
    const {data} = await getCompanyApi()
    companyList.value = data.map(item => {
      item.companyCode = item.companyCode * 1
      return item
    }) || []
  }
  const getCurrentMenu = async () => {
    const {data} = await getCurrentMenuApi()
    menuDataList.value = parseTreeData(data) || []
  }
  const selectPerson = async () => {
    const {data} = await selectPersonApi()
    peopleTreeData.value = parsePeopleTreeData(data)
  }
  const selectPeople = () => {
    dialogVisible.value = true
  }

  const parsePeopleTreeData = (data) => {
    const result = []
    data.forEach(node => {
      node.id = node.deptId
      node.label = node.deptName
      node.type = node.type?node.type:'dept'
      console.log('节点ID:', node.id, '节点名称：', node.name);
      if(node.user && node.user.length > 0 && node.children&& node.children.length > 0){
        node.user.forEach(ite => {
          node.children.push({
            deptId: ite.userId,
            deptName: ite.userName,
            parentId: node.deptId,
            type: 'user'
          })
        })
      }
      if (node.user && node.user.length > 0 && (!node.children || !node.children.length)) {
        node.children = []
        node.user.forEach(ite => {
          node.children.push({
            deptId: ite.userId,
            deptName: ite.userName,
            parentId: node.deptId,
            type: 'user'
          })
        })
      }
      if (node.children && node.children.length > 0) {
        parsePeopleTreeData(node.children);
      }
      result.push(node)
    });
    console.log(result, 3333)
    return result
  }

  const parseTreeData = (data) => {
    const result = []
    data.forEach(node => {
      node.id = node.value
      console.log('节点ID:', node.id, '节点名称：', node.name);
      if (node.children && node.children.length > 0) {
        parseTreeData(node.children);
      }
      result.push(node)
    });
    return result
  }
  const personList = ref([])
  const getPersonListApi = async() => {
    const {data} = await getPersonList()
    console.log(data.list, 4444444)
    personList.value = data.list || []
  }

  onMounted(() => {
    getCompany()
    getCurrentMenu()
    selectPerson()
    getPersonListApi()
    // selectPersonOld()
  })
  return {
    authorityForm,
    defaultProps,
    menuDataList,
    companyList,
    dialogVisible,
    peopleTreeData,
    detailVisible,
    treeRef,
    personList,
    selectPeople,
    handleClose
  }
}

export const useAuthorityIndex = () => {
  const tableRef = ref()
  const searchState = reactive({})
  const onSearch = () => {
    tableRef.value.reset(searchState)
  }
  const handleDeleteRole = async(id) => {
    ElMessageBox.confirm(
      `确认要删除当前角色吗?`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      deleteRole(id)
    })
  }
  const deleteRole = async(id) => {
    const {data} = await deleteRoleApi(id)
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    onSearch()
  }
  return {
    tableRef,
    onSearch,
    handleDeleteRole
  }
}

export const useAuthority = () => {
  const addAddAuthorityStore = useAddAuthority()
  const authorityIndexStore = useAuthorityIndex()
  return {
    addAddAuthorityStore,
    authorityIndexStore
  }
}
